package com.ezjie.ielts.module_read;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ezjie.ielts.R;
import com.ezjie.ielts.constant.Constants;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.core.http.ServerInterfaceDefinition;
import com.ezjie.ielts.core.spfs.SharedPrefHelper;
import com.ezjie.ielts.db.FullTextInfoDB;
import com.ezjie.ielts.db.GroupInfoDB;
import com.ezjie.ielts.db.UserInfoDB;
import com.ezjie.ielts.model.FullTextInfo;
import com.ezjie.ielts.model.GroupInfo;
import com.ezjie.ielts.model.ReadClassifyQuestionInfo;
import com.ezjie.ielts.model.SubmitGroupInfo;
import com.ezjie.ielts.model.SubmitQuestionInfo;
import com.ezjie.ielts.module_read.originpager.ReadOriginPagerFragment;
import com.ezjie.ielts.task.ErrorQuestionTask;
import com.ezjie.ielts.task.ReadClassifyTask;
import com.ezjie.ielts.task.ReadSubjectsTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.LayoutManager;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.OnDialogBtnClickImpl;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.widget.SerializableMap;
import com.ezjie.ielts.widget.TitleTextView;
import com.ezjie.login.model.UserDetail;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

public class ReadAllPracticeActivity extends BaseFragmentActivity {

	@ViewInject(R.id.iv_topbar_back)
	private ImageView iv_topbar_back;
	@ViewInject(R.id.tv_topbar_title)
	private TitleTextView tv_topbar_title;
	@ViewInject(R.id.tv_normal_topbar_title)
	private TextView tv_normal_topbar_title;
	@ViewInject(R.id.tv_originpage)
	private TextView tv_originpage;
	@ViewInject(R.id.fragment_originpager)
	private FrameLayout fragment_originpager;
	@ViewInject(R.id.rl_layout_back)
	private View rl_layout_back;
	@ViewInject(R.id.btn_read_back)
	private Button btn_read_back;
	@ViewInject(R.id.tv_complete_content)
	private TextView tv_complete_content;
	@ViewInject(R.id.tv_complete_title)
	private TextView tv_complete_title;

	private Context mContext;
	private long duration = 250;
	private String type;
	private String category_id;
	private String fromActivity;
	private ReadOriginPagerFragment pagerFragment;
	private Fragment practiceFragment;
	public String mOriginStr = "";

	private ArrayList<GroupInfo> data = new ArrayList<GroupInfo>();
	private ArrayList<FullTextInfo> origindata = new ArrayList<FullTextInfo>();
	private ArrayList<String> idLists = new ArrayList<String>();

	private ReadClassifyTask mReadClassifyTask;
	private ReadSubjectsTask mSubjectsTask;
	private ErrorQuestionTask mErrorQuestionTask;

	private GroupInfoDB groupDB;
	private FullTextInfoDB fullTextDB;
	private int position;
	private int total_num;
	private String error_type;

	private UserDetail userDetail;

	public Map<Integer, SubmitGroupInfo> mSubmitReadAnswer = new LinkedHashMap<Integer, SubmitGroupInfo>();
	public Map<Integer, GroupInfo> mInstantReportGroupInfoList = new LinkedHashMap<Integer, GroupInfo>(); // 即时报告所需数据

	private String detailType = "";
	private int currentPosition;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0) {
				Toast.makeText(mContext, "数据库操作完成", 1).show();

			} else if (msg.what == 1) {
				AppUtil.dismissProgressDialog();
				finish();
				sendBroadcast(new Intent(Constants.REFRESH_CLASSFIY_DATA_ACTION));
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_allpractice);
		ViewUtils.inject(this);

		type = getIntent().getStringExtra(Constants.READ_TYPE);
		position = getIntent().getIntExtra(Constants.READ_POSITION, 0);
		total_num = getIntent().getIntExtra(Constants.READ_TOTAL, 0);
		category_id = getIntent().getStringExtra(Constants.READ_ID);
		error_type = getIntent().getStringExtra(Constants.READ_ERROR_TYPE);
		fromActivity = getIntent().getStringExtra(Constants.READ_FROM);
		mSubjectsTask = new ReadSubjectsTask(this);
		mReadClassifyTask = new ReadClassifyTask(this);
		mErrorQuestionTask = new ErrorQuestionTask(this);
		groupDB = new GroupInfoDB(this);
		fullTextDB = new FullTextInfoDB(this);
		UserInfoDB userInfoDB = new UserInfoDB(this);
		userDetail = userInfoDB.queryLoginUser();

		mContext = this;

		LayoutManager.getScreenConstant(this);
		init();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_ALLPRACTICE);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_ALLPRACTICE);
	}
	

	/**
	 * 设置界面标题
	 * 
	 * @param resId
	 */
	public void resetTopTitle(int resId) {
		tv_topbar_title.setText(resId);
		tv_topbar_title.setVisibility(View.VISIBLE);
		tv_normal_topbar_title.setVisibility(View.GONE);
	}

	private void init() {

		if (Constants.READ_FROM_VALUE1.equals(fromActivity)) {
			tv_topbar_title.setText(R.string.exam_listen);
			tv_originpage.setVisibility(View.GONE);
		} else if (Constants.READ_FROM_VALUE3.equals(fromActivity)) {
			listenerSoftInput();
			tv_topbar_title.setText(R.string.error_practices);
		} else {
			listenerSoftInput();
			tv_topbar_title.setText(R.string.exam_reading);
		}

		if (Constants.READ_FROM_VALUE3.equals(fromActivity)) {
			tv_topbar_title.setText(R.string.read_error_title);
		}
		iv_topbar_back.setOnClickListener(this);
		tv_originpage.setOnClickListener(this);

		if (null != type) {
			if (SharedPrefHelper.getInstance().getUpdatetime(
					ServerInterfaceDefinition.OPT_READ_CLASSIFY_QUESTION + type)
					&& NetworkUtil.isNetworkAvailable(mContext)) {
				mReadClassifyTask.getReadClassifyQuestion(type, new HttpRequestAbstractCallBack(this,true) {
					@Override
					public void onStartCallBack() {
						super.onStartCallBack();
						AppUtil.showProgressDialog(mContext);
					}

					@Override
					public void onSuccessCallBack(String result) {
						super.onSuccessCallBack(result);
						LogUtils.d(result);
						AppUtil.dismissProgressDialog();

						try {
							final ReadClassifyQuestionInfo info = JSON.parseObject(result,
									ReadClassifyQuestionInfo.class);
							if (null != info.data && null != info.data.questions) {

								new Thread(new Runnable() { // 缓存到数据库中
											@Override
											public void run() {
												try {
													groupDB.replaceInto(info.data.questions);
													fullTextDB.replaceInto(info.data.full_contents);
													SharedPrefHelper
															.getInstance()
															.setUpdatetime(
																	ServerInterfaceDefinition.OPT_READ_CLASSIFY_QUESTION
																			+ type);
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
										}).start();

								data.addAll(info.data.questions);
								origindata = info.data.full_contents;

								if (data.size() > position) {
									data.subList(0, position).clear();
								}

								if (data.size() > 0) {
									detailType = data.get(0).group_type;// 加载第一个题型

									initPracticePager(0);
									initOriginPager();
								}

							}
						} catch (Exception e) {
							LogUtils.exception(e);
						}
						// AppUtil.dismissProgressDialog();
					}

					@Override
					public void onFailureCallBack(HttpException error, String msg) {
						super.onFailureCallBack(error, msg);
						LogUtils.e(msg);
						AppUtil.dismissProgressDialog();
						AppUtil.showToast(ReadAllPracticeActivity.this, R.string.load_net_data_failure);
					}
				});
			} else {
				if (Constants.READ_FROM_VALUE1.equals(fromActivity)) {
					data = groupDB.query(position, type, category_id, 1);
				} else {
					data = groupDB.query(position, type, category_id, 0);
				}
				for (int i = 0; i < data.size(); i++) {
					idLists.add(data.get(i).category_id);
				}
				origindata = fullTextDB.query(idLists);
				if (data.size() > 0) {
					detailType = data.get(0).group_type;// 加载第一个题型

					initPracticePager(0);
					initOriginPager();
				}
			}
		} else if (null != category_id) {
			if (SharedPrefHelper.getInstance().getUpdatetime(
					ServerInterfaceDefinition.OPT_READ_CLASSIFY_QUESTION + category_id)
					&& NetworkUtil.isNetworkAvailable(mContext)) {
				mSubjectsTask.getReadSubjectQuestion(category_id, new HttpRequestAbstractCallBack(this,true) {
					@Override
					public void onStartCallBack() {
						super.onStartCallBack();
						AppUtil.showProgressDialog(mContext);
					}

					@Override
					public void onSuccessCallBack(String result) {
						super.onSuccessCallBack(result);
						LogUtils.d(result);
						AppUtil.dismissProgressDialog();

						try {
							ReadClassifyQuestionInfo info = JSON.parseObject(result, ReadClassifyQuestionInfo.class);
							if (null != info.data && null != info.data.questions) {
								data = info.data.questions;
								origindata = info.data.full_contents;
								if (data.size() > 0) {
									detailType = data.get(0).group_type;// 加载第一个题型

									initPracticePager(0);
									initOriginPager();
								}

								new Thread(new Runnable() {
									@Override
									public void run() {
										try {
											groupDB.replaceInto(data);
											fullTextDB.replaceInto(origindata);
											SharedPrefHelper.getInstance().setUpdatetime(
													ServerInterfaceDefinition.OPT_READ_CLASSIFY_QUESTION + category_id);
										} catch (Exception e) {
											e.printStackTrace();
										}
										// mHandler.sendEmptyMessage(0);
									}
								}).start();
							}
						} catch (Exception e) {
							LogUtils.exception(e);
						}
					}

					@Override
					public void onFailureCallBack(HttpException error, String msg) {
						super.onFailureCallBack(error, msg);
						LogUtils.e(msg);
						AppUtil.dismissProgressDialog();
						AppUtil.showToast(ReadAllPracticeActivity.this, R.string.load_net_data_failure);
					}
				});
			} else {
				if (Constants.READ_FROM_VALUE1.equals(fromActivity)) {
					data = groupDB.query(0, type, category_id, 1);
				} else {
					data = groupDB.query(0, type, category_id, 0);
				}
				idLists.add(category_id);
				origindata = fullTextDB.query(idLists);
				if (data.size() > 0) {
					detailType = data.get(0).group_type;// 加载第一个题型

					initPracticePager(0);
					initOriginPager();
				}
			}
		} else if (null != error_type) {
			Bundle bundle = getIntent().getBundleExtra(Constants.READ_ERROR_BUNDLE);

			if (null != bundle) {
				data = (ArrayList<GroupInfo>) bundle.getSerializable(Constants.READ_SETDATA_PRACTICE);
				origindata = (ArrayList<FullTextInfo>) bundle.getSerializable(Constants.READ_SETDATA_ORIGIN);
			}

			if (data.size() > 0) {
				detailType = data.get(0).group_type;// 加载第一个题型

				initPracticePager(0);
				initOriginPager();
			}
		}
	}

	private void initPracticePager(int position) {

		if (Constants.READ_FROM_VALUE.equals(fromActivity)) {

			tv_topbar_title.setVisibility(View.GONE);
			tv_normal_topbar_title.setVisibility(View.VISIBLE);

			if (Constants.ReadClassifyType.CHART_COMPLETION.equals(type)) {
				tv_normal_topbar_title.setText(R.string.tab_chart_completion);
			} else if (Constants.ReadClassifyType.MATCHING.equals(type)) {
				tv_normal_topbar_title.setText(R.string.matching);
			} else if (Constants.ReadClassifyType.LIST_OF_HEADINGS.equals(type)) {
				tv_normal_topbar_title.setText(R.string.list_of_headings);
			} else if (Constants.ReadClassifyType.TRUE_OR_FALSE.equals(type)) {
				tv_normal_topbar_title.setText(R.string.true_or_false);
			} else if (Constants.ReadClassifyType.CHOICE.equals(type)) {
				tv_normal_topbar_title.setText(R.string.all_choice);
			} else if (Constants.ReadClassifyType.SUMMARY.equals(type)) {
				tv_normal_topbar_title.setText(R.string.summary);
			} else if (Constants.ReadClassifyType.SHORT_ANSWER.equals(type)) {
				tv_normal_topbar_title.setText(R.string.short_answer);
			} else if (Constants.ReadClassifyType.SENTENCE_COMPLETION.equals(type)) {
				tv_normal_topbar_title.setText(R.string.sentence_completion);
			}
		} else {
			tv_topbar_title.setVisibility(View.VISIBLE);
			tv_normal_topbar_title.setVisibility(View.GONE);
		}

		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		Bundle bundle = new Bundle();
		bundle.putString(Constants.READ_FROM, fromActivity);

		int tmptype = 0;
		try {
			tmptype = Integer.valueOf(detailType);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		if (tmptype >= 1 && tmptype <= 14) {
			practiceFragment = new AllExercisesFragment(detailType, new MySwitchListener(), position);
			bundle.putString(Constants.READ_FROM, fromActivity);
			bundle.putString(Constants.READ_START_TIME, String.valueOf(System.currentTimeMillis()));
			bundle.putSerializable(Constants.READ_SETDATA_PRACTICE, data);
		} else {
			practiceFragment = new Fragment();
		}
		practiceFragment.setArguments(bundle);
		transaction.replace(R.id.fragment_practice, practiceFragment);
		transaction.commit();
	}

	public class MySwitchListener implements OnSwitchListener {
		@Override
		public void changeFragment(int position) {
			InputMethodManager inputManager = (InputMethodManager) mContext
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
			currentPosition = position;
			if (data.size() > position) {
				closeAudio();
				detailType = data.get(position).group_type;
				initPracticePager(position);

				pagerFragment.resetDatas(data.get(position).category_id);

			} else if (null != error_type || (null != fromActivity && Constants.READ_FROM_VALUE.equals(fromActivity))) {
				rl_layout_back.setVisibility(View.VISIBLE);
				iv_topbar_back.setVisibility(View.GONE);
				btn_read_back.setOnClickListener(ReadAllPracticeActivity.this);
				if (null != error_type) {
					btn_read_back.setText(R.string.read_complete_back);
					tv_complete_title.setText(R.string.read_complete_title2);
					tv_complete_content.setText(R.string.read_complete_content2);
				} else {
					btn_read_back.setText(R.string.read_complete_classfiy_back);
					tv_complete_title.setText(R.string.read_complete_title);
					tv_complete_content.setText(R.string.read_complete_content);
				}
			} else {
				closeAudio();
				JSONArray array = new JSONArray();
				for (Integer key : mSubmitReadAnswer.keySet()) {
					Object obj = JSONObject.toJSON(mSubmitReadAnswer.get(key));
					array.add(obj);
				}
				if (null != fromActivity && Constants.READ_FROM_VALUE1.equals(fromActivity)) {
					// 友盟统计
					MobclickAgent.onEvent(mContext, "listenExam_submit");
					mReadClassifyTask.submitListenAnswer(category_id, array.toJSONString(),
							new HttpRequestAbstractCallBack(mContext,true) {
								@Override
								public void onStartCallBack() {
									super.onStartCallBack();
								}

								@Override
								public void onSuccessCallBack(String result) {
									super.onSuccessCallBack(result);
									LogUtils.d(result);
								}

								@Override
								public void onFailureCallBack(HttpException error, String msg) {
									super.onFailureCallBack(error, msg);
									LogUtils.e(msg);
									AppUtil.showToast(mContext, R.string.load_net_data_failure);
								}
							});

				} else {
					// 友盟统计
					MobclickAgent.onEvent(mContext, "readExam_submit");
					mReadClassifyTask.submitReadAnswer(category_id, array.toJSONString(),
							new HttpRequestAbstractCallBack(mContext,true) {
								@Override
								public void onStartCallBack() {
									super.onStartCallBack();
								}

								@Override
								public void onSuccessCallBack(String result) {
									super.onSuccessCallBack(result);
									LogUtils.d(result);
								}

								@Override
								public void onFailureCallBack(HttpException error, String msg) {
									super.onFailureCallBack(error, msg);
									LogUtils.e(msg);
									AppUtil.showToast(mContext, R.string.load_net_data_failure);
								}
							});
				}

				Intent intent = new Intent(mContext, ReadInstantReportActivity.class);
				Bundle bundle = new Bundle();
				SerializableMap tmpmap = new SerializableMap();
				tmpmap.setMap(mInstantReportGroupInfoList);
				bundle.putSerializable(Constants.READ_INSTANT_REPORT_ANSWER, tmpmap);
				SerializableMap tmpmap2 = new SerializableMap();
				tmpmap2.setMap(mSubmitReadAnswer);
				bundle.putSerializable(Constants.READ_INSTANT_REPORT_SUBMIT_ANSWER, tmpmap2);
				bundle.putSerializable(Constants.READ_SETDATA_ORIGIN, origindata);
				intent.putExtra(Constants.READ_INSTANT_REPORT_BUNDLE, bundle);
				startActivity(intent);

				finish();
			}
		}
	}

	private void initOriginPager() {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		pagerFragment = new ReadOriginPagerFragment();
		Bundle bundle = new Bundle();
		bundle.putSerializable(Constants.READ_SETDATA_ORIGIN, origindata);
		bundle.putString(Constants.READ_ORIGIN_INDEX, data.get(0).category_id);
		pagerFragment.setArguments(bundle);
		transaction.replace(R.id.fragment_originpager, pagerFragment);
		transaction.commit();
	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.iv_topbar_back:
			toBack();
			break;
		case R.id.tv_originpage:
			if(fromActivity.equals(Constants.READ_FROM_VALUE3)){
				if(currentPosition < mSubmitReadAnswer.size()){
					MobclickAgent.onEvent(mContext, "ErrorPracticeAnswer_readText");
				}else {
					MobclickAgent.onEvent(mContext, "ErrorPractice_readText");
				}
			}else if(fromActivity.equals(Constants.READ_FROM_VALUE2)){
				MobclickAgent.onEvent(mContext, "readExam_readText");
			}else if(fromActivity.equals(Constants.READ_FROM_VALUE)){
				if(currentPosition < mSubmitReadAnswer.size()){
					MobclickAgent.onEvent(mContext, "readPracticeAnswer_readText");
				}else {
					MobclickAgent.onEvent(mContext, "readPractice_readText");
				}
			}
			toggleOriginPager();
			break;
		case R.id.btn_read_back:
			toBack();
			break;
		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		if (fragment_originpager.getVisibility() == View.INVISIBLE) {
			if (Constants.READ_FROM_VALUE3.equals(fromActivity)) {
				SharedPrefHelper.getInstance().setFinishNum(userDetail.uid,
						SharedPrefHelper.getInstance().getFinishNum(userDetail.uid) + mSubmitReadAnswer.size());
			}
			toBack();
		} else {
			toggleOriginPager();
		}
	}

	private void closeAudio() {

		if (practiceFragment instanceof AllExercisesFragment) {
			((AllExercisesFragment) practiceFragment).onFragmentBack();
		}
	}

	private void toBack() {

		if (null != fromActivity
				&& (Constants.READ_FROM_VALUE.equals(fromActivity) || Constants.READ_FROM_VALUE3.equals(fromActivity))) {

			final JSONArray array = new JSONArray();
			for (Integer key : mSubmitReadAnswer.keySet()) {
				Object obj = JSONObject.toJSON(mSubmitReadAnswer.get(key));
				array.add(obj);
			}

			if (array.size() > 0) {
				AppUtil.showProgressDialog(mContext);
				if (null != fromActivity && Constants.READ_FROM_VALUE.equals(fromActivity)) {
					int mposition = mSubmitReadAnswer.size() + position;
					if (total_num <= position) {
						mposition = mSubmitReadAnswer.size();
					}

					if (total_num <= mposition) {
						mposition = 0;
					}
					mReadClassifyTask.submitReadClassifyAnswer(type, array.toJSONString(), mposition + "",
							new HttpRequestAbstractCallBack(mContext,true) {
								@Override
								public void onStartCallBack() {
									super.onStartCallBack();
								}

								@Override
								public void onSuccessCallBack(String result) {
									super.onSuccessCallBack(result);
									LogUtils.d(result);
								}

								@Override
								public void onFailureCallBack(HttpException error, String msg) {
									super.onFailureCallBack(error, msg);
									LogUtils.e(msg);
									AppUtil.showToast(mContext, R.string.load_net_data_failure);
								}
							});
				} else if (null != error_type) {
					mErrorQuestionTask.submitErrorQuestions(array.toJSONString(), new HttpRequestAbstractCallBack(mContext,true) {
						@Override
						public void onStartCallBack() {
							super.onStartCallBack();
						}

						@Override
						public void onSuccessCallBack(String result) {
							super.onSuccessCallBack(result);
							int rightnum = 0;
							for (int i = 0; i < array.size(); i++) {
								SubmitGroupInfo submitGroupInfo = array.getObject(i, SubmitGroupInfo.class);
								for (int j = 0; j < submitGroupInfo.questions.size(); j++) {
									SubmitQuestionInfo submitQuestionInfo = submitGroupInfo.questions.get(j);
									if (submitQuestionInfo.is_right.equals("false")) {
										break;
									}
									if (j == submitGroupInfo.questions.size() - 1) {
										rightnum++;
									}
								}
							}

							SharedPrefHelper.getInstance().setFinishNum(userDetail.uid,
									Integer.valueOf(SharedPrefHelper.getInstance().getFinishNum(userDetail.uid)) + rightnum + "");
							LogUtils.d(result);
						}

						@Override
						public void onFailureCallBack(HttpException error, String msg) {
							super.onFailureCallBack(error, msg);
							LogUtils.e(msg);
							AppUtil.showToast(mContext, R.string.load_net_data_failure);
						}
					});
				}
				mHandler.sendEmptyMessageDelayed(1, 500);
			} else {
				finish();
			}
		} else {

			AppUtil.showAppDialog(this, R.string.read_dialog_msg, "", R.string.read_dialog_yes,
					R.string.read_dialog_no, 0, false, new OnDialogBtnClickImpl() {

						@Override
						public void onYesClick() {
							if(fromActivity.equals(Constants.READ_FROM_VALUE1)){
								// 友盟统计
								MobclickAgent.onEvent(mContext, "listenExam_quitYesOrNot");
							}else{
								// 友盟统计
								MobclickAgent.onEvent(mContext, "readExam_quitYesOrNo");
							}
							closeAudio();
							finish();
						}
						
						@Override
						public void onNoClick() {
							super.onNoClick();
							if(fromActivity.equals(Constants.READ_FROM_VALUE1)){
								// 友盟统计
								MobclickAgent.onEvent(mContext, "listenExam_quitYesOrNot");
							}else{
								// 友盟统计
								MobclickAgent.onEvent(mContext, "readExam_quitYesOrNo");
							}
						}
					});
		}
	}

	// 切出或隐藏原文
	private void toggleOriginPager() {
		if (fragment_originpager.getVisibility() == View.INVISIBLE) {
			AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
			alphaAnimation.setDuration(duration * 2);
			fragment_originpager.startAnimation(alphaAnimation);
			alphaAnimation.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					tv_originpage.setBackgroundResource(R.drawable.original_pager_close);
					fragment_originpager.setVisibility(View.VISIBLE);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
				}
			});
		} else {
			AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
			alphaAnimation.setDuration(duration * 2);
			fragment_originpager.startAnimation(alphaAnimation);
			alphaAnimation.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					tv_originpage.setBackgroundResource(R.drawable.original_pager);
					fragment_originpager.setVisibility(View.INVISIBLE);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
				}
			});
		}

	}

	// 监听软键盘弹出，原文按钮出现与否，与练习的fragment绑定
	private void listenerSoftInput() {
		final View activityRootView = findViewById(R.id.fragment_practice);
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
				if (heightDiff > 300) {// 如果高度差超过300像素，就很有可能是有软键盘...
					tv_originpage.setVisibility(View.GONE);
				} else {
					tv_originpage.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	public interface OnTouchEventGestureListener {
		public boolean onTouchEvent(MotionEvent event);
	};

	/**
	 * 以下的几个方法用来，让fragment能够监听touch事件
	 */
	private Set<OnTouchEventGestureListener> onTouchListeners = new HashSet<OnTouchEventGestureListener>();

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		for (OnTouchEventGestureListener listener : onTouchListeners) {
			listener.onTouchEvent(event);
		}
		return super.dispatchTouchEvent(event);
	}

	public void registerOnTouchEventGestureListener(OnTouchEventGestureListener onTouchListener) {
		onTouchListeners.add(onTouchListener);
	}

	public void unregisterOnTouchEventGestureListener(OnTouchEventGestureListener onTouchListener) {
		onTouchListeners.remove(onTouchListener);
	}

	public interface OnSwitchListener {
		void changeFragment(int position);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

}
